package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.heima.common.constants.WemediaConstants;
import com.heima.common.constants.WmNewsMessageConstants;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;

import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmDownOrUpDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    /**
     * 分页查询文章
     *
     * @param wmNewsPageReqDto
     * @return
     */
    @Override
    public ResponseResult pageNews(WmNewsPageReqDto wmNewsPageReqDto) {
        if (wmNewsPageReqDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmNews> lqwWN = new LambdaQueryWrapper<>();
        //校验参数
        wmNewsPageReqDto.checkParam();//不为空原有的数据,为空默认page=1,size=10
        lqwWN.eq(WmThreadLocalUtil.getUser().getApUserId() != null, WmNews::getUserId, WmThreadLocalUtil.getUser().getApUserId());
        IPage<WmNews> page = new Page<>();
        page.setPages(wmNewsPageReqDto.getPage());
        page.setSize(wmNewsPageReqDto.getSize());

        //状态不等于null就查询所有状态
        lqwWN.eq(wmNewsPageReqDto.getStatus() != null, WmNews::getStatus, wmNewsPageReqDto.getStatus());
        //频道
        lqwWN.eq(wmNewsPageReqDto.getChannelId() != null, WmNews::getChannelId, wmNewsPageReqDto.getChannelId());
        //关键字
        lqwWN.like(wmNewsPageReqDto.getKeyword() != null, WmNews::getTitle, wmNewsPageReqDto.getKeyword());
        //开始时间结束时间没有传默认现在之后
        if (wmNewsPageReqDto.getBeginPubDate() != null && wmNewsPageReqDto.getEndPubDate() != null) {
            lqwWN.between(WmNews::getPublishTime, wmNewsPageReqDto.getBeginPubDate(), wmNewsPageReqDto.getEndPubDate());
        }

        //根据时间排序
        lqwWN.orderByDesc(WmNews::getPublishTime);
        page = page(page, lqwWN);
        ResponseResult responseResult = new PageResponseResult(wmNewsPageReqDto.getPage(), wmNewsPageReqDto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService  wmNewsTaskService;

    /**
     * 添加文章
     *
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult submit(WmNewsDto wmNewsDto) {
        //参数校验(没有内容也不能添加)
        if (wmNewsDto == null || wmNewsDto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //拷贝数据
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);
        //判断是不是自动
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //是自动(后面要换成具体的图片数量)
            wmNews.setType(null);
        }
        //将数据添加到数据库中(如果是草稿就就结束,草稿没有必要保持关系表)
        saveOrUpdateWmNews(wmNews);
        if (wmNews.getStatus().equals(WmNews.Status.NORMAL.getCode())) {
            //草稿就结束
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //不是草稿保持关系表
        //获取文章内容的图片信息(图片的url)
        List<String> materials = ectractUrlInfo(wmNewsDto.getContent());
        //为文章内容保存相关信息
        saveRelativeInfoForContent(materials, wmNews.getId());
        //不是草稿，保存文章封面图片与素材的关系，如果当前布局是自动，需要匹配封面图片
        saveRelativeInfoForCover(wmNewsDto, wmNews, materials);
        //审核文章
//        wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addWmNewsToTask(wmNews);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //为文章封面保存相关信息
    private void saveRelativeInfoForCover(WmNewsDto wmNewsDto, WmNews wmNews, List<String> materials) {
        List<String> images = wmNewsDto.getImages();
        //如果当前封面类型为自动，则设置封面类型的数据
        //自动
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            //判断多图
            if (materials.size() >= 3) {
                //多图
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                //将集合里的前3张图片放入集合里
                images = materials.stream().limit(3).collect(Collectors.toList());
            } else if (materials.size() >= 1 && materials.size() < 3) {
                //  单图
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                //将集合里的前3张图片放入集合里
                images = materials.stream().limit(1).collect(Collectors.toList());
            } else {
                //无图
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }
            //修改文章
            if (images != null && images.size() > 0) {
                //images被操作过(且有内容)将集合里的元素拿出来以,分隔转字符转
                wmNews.setImages(StringUtils.join(images, ","));
            }
            updateById(wmNews);
        }
        //非自动(images就有内容)
        if (images != null && images.size() > 0) {
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_COVER_REFERENCE);
        }
    }

    //为文章内容保存相关信息
    private void saveRelativeInfoForContent(List<String> materials, Integer newsId) {
        saveRelativeInfo(materials, newsId, WemediaConstants.WM_CONTENT_REFERENCE);// 无图
    }

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    //保存文章图片与素材的关系到数据库中
    private void saveRelativeInfo(List<String> materials, Integer newsId, Short type) {
        //通过图片的url查询素材的id
        if (materials != null && !materials.isEmpty()) {
            List<WmMaterial> wmMaterialListDB = wmMaterialMapper.selectList(Wrappers.<WmMaterial>lambdaQuery().in(WmMaterial::getUrl, materials));
            if (wmMaterialListDB.size() != materials.size()) {
                throw new CustomException(AppHttpCodeEnum.MATERIASL_REFERENCE_FAIL);
            }
            List<Integer> materialIds = wmMaterialListDB.stream().map(wmMaterial -> {
                return wmMaterial.getId();
            }).collect(Collectors.toList());
            //保存关系表
            wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);
        }

    }

    //获取文章内容里的图片信息
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();
        //将内容里的json放到map里
        List<Map> mapList = JSON.parseArray(content, Map.class);
        //获取图片信息
        mapList.stream().forEach(map -> {
            //通过type键找image值
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        });
        return materials;
    }


    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    //保存文章数据
    private void saveOrUpdateWmNews(WmNews wmNews) {
        //补全属性
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);//默认上架
        if (wmNews.getId() == null) {
            //新增
            save(wmNews);
        } else {
            //删除关联关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    /**
     * 查看文章详情
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getByNewId(Integer id) {
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(wmNews);
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteNews(Integer id) {
        if (id == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        WmNews wmNews = getById(id);
        if (wmNews == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        if (WmNews.Status.PUBLISHED.getCode() == (wmNews.getStatus()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PUBLISH_ARTICLE_NO_DELETE);

        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 下架或上架
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if (null == dto) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews = wmNewsMapper.selectById(wmNews);
        if (wmNews.getStatus() != WmNews.Status.PUBLISHED.getCode()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前文章不是发布状态，不能上下架");
        }
        if (null == dto.getId()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        LambdaUpdateWrapper<WmNews> set =
                Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable());
        wmNewsMapper.update(wmNews, set);
        // 传给article
        WmDownOrUpDto wmDownOrUpDto = new WmDownOrUpDto();
        wmDownOrUpDto.setArticleId(wmNews.getArticleId());
        wmDownOrUpDto.setIsDown(wmNews.getEnable() == 1);
        kafkaTemplate.send("wmNews-topic", JSON.toJSONString(wmDownOrUpDto));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
